﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Excel = Microsoft.Office.Interop.Excel;
using DesktopDOHS.appData.Schemas;

namespace DesktopDOHS
{
    public partial class frmExportFiles : Form
    {
        public frmExportFiles()
        {
            InitializeComponent();
        }

        private List<MensagemDOHSExamesDOHS> lstLogs = new List<MensagemDOHSExamesDOHS>();

        private XmlDocument serializaXMLTemp()
        {
            XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
            List<MensagemDOHSExamesDOHS> lstExamesAux = new List<MensagemDOHSExamesDOHS>();
            foreach (ListViewItem item in lstExams.SelectedItems)
            {
                TextReader tr = new StreamReader(item.SubItems[4].Text);
                MensagemDOHS msgDOHSAux = (MensagemDOHS)xs.Deserialize(tr);
                tr.Close();
                lstExamesAux.Add(msgDOHSAux.ExamesDOHS[0]);
            }
            MensagemDOHS msgDOHS = new MensagemDOHS();
            msgDOHS.ExamesDOHS = new MensagemDOHSExamesDOHS[lstExamesAux.Count];
            msgDOHS.ExamesDOHS = lstExamesAux.ToArray();
            Stream str = new MemoryStream();
            xs.Serialize(str, msgDOHS);
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(str);
            return xdoc;
        }

        private void frmExportFiles_Load(object sender, EventArgs e)
        {
            /*DirectoryInfo dir = new DirectoryInfo(Application.StartupPath + "\\Mensagens\\Log");
            FileInfo[] xmlFiles = dir.GetFiles("*.oms");
            XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
            MensagemDOHS LogAux = new MensagemDOHS();
            DataTable dt;
            string DataExame;
            foreach (FileInfo file in xmlFiles)
            {
                XmlReader xr = XmlReader.Create(file.FullName);
                LogAux = (MensagemDOHS)xs.Deserialize(xr);
                foreach (MensagemDOHSExamesDOHS cabecalho in LogAux.ExamesDOHS)
                { 
                    lstCabecalho.Add(cabecalho.Cabecalho);
                }
                xr.Close();
            }*/
            XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
            TextReader tr = new StreamReader(Application.StartupPath + "\\Mensagens\\Log\\MsgDOHSLog.oms");
            MensagemDOHS msgDOHSLog = (MensagemDOHS)xs.Deserialize(tr);
            tr.Close();
            foreach (MensagemDOHSExamesDOHS exame in msgDOHSLog.ExamesDOHS)
            {
                //Examinador - Data - Localização Geográfica - Tipo Local
                string DataExame = Convert.ToDateTime(exame.Cabecalho.DataLevantamento).ToString("dd/MM/yyyy");
                DataTable dt = appData.Commands.buscaRegistro("Examinador", "Nome", exame.Cabecalho.CodExaminador, DataExame);
                if (dt.Rows.Count == 0)
                    lstExams.Items.Add(exame.Cabecalho.CodExaminador);
                else
                    lstExams.Items.Add(dt.Rows[0].ItemArray[2].ToString());
                lstExams.Items[lstExams.Items.Count - 1].ImageIndex = 0;
                lstExams.Items[lstExams.Items.Count - 1].SubItems.Add(DataExame);
                dt = appData.Commands.buscaRegistro("LocGeo", "LocGeo", exame.Cabecalho.LocGeo, DataExame);
                if (dt.Rows.Count == 0)
                    lstExams.Items[lstExams.Items.Count - 1].SubItems.Add(exame.Cabecalho.LocGeo);
                else
                    lstExams.Items[lstExams.Items.Count - 1].SubItems.Add(dt.Rows[0].ItemArray[2].ToString());
                if (exame.Cabecalho.TipoLoc == "1")
                    lstExams.Items[lstExams.Items.Count - 1].SubItems.Add("Urbano");
                if (exame.Cabecalho.TipoLoc == "2")
                    lstExams.Items[lstExams.Items.Count - 1].SubItems.Add("Periurbano");
                if (exame.Cabecalho.TipoLoc == "3")
                    lstExams.Items[lstExams.Items.Count - 1].SubItems.Add("Rural");
                lstExams.Items[lstExams.Items.Count - 1].SubItems.Add(((MensagemDOHSExamesDOHSMsgLog)exame.Item).Path);
            }
        }

        private void abreDocExcel(string filePath)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "EXCEL";
            proc.StartInfo.Arguments = "\"" + filePath + "\"";
            proc.Start();
        }

        private void Export(string basePath, string filePath)
        {
            XmlDocument xdoc = this.serializaXMLTemp();
            Excel.Application excelApp = new Excel.Application();
            try
            {
                Excel.Workbook excelWB = excelApp.Workbooks.Open(basePath, false, false, System.Type.Missing,
                    System.Type.Missing, System.Type.Missing, true, System.Type.Missing, System.Type.Missing,
                    true, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
                    System.Type.Missing);

                excelApp.ActiveWorkbook.RefreshAll();
                excelApp.Workbooks.Application.ActiveWorkbook.RefreshAll();
                excelWB.XmlMaps[1].ImportXml(xdoc.OuterXml, false);
                excelWB.Close(true, filePath, false);
                excelApp.Quit();

                this.abreDocExcel(filePath);
            }
            catch (Exception ex)
            { throw ex; }
        }

        private void lstExams_DoubleClick(object sender, EventArgs e)
        {
            //ID - DataNasc - Idade - GrupoEtario- Sexo - GrupoEtnico - Ocupação - ContraInd - Duplicata - OutrosDados1 - OutrosDados2
            if (lstExams.SelectedIndices.Count == 1)
            {
                lblTopo.Text = lstExams.Items[lstExams.SelectedIndices[0]].Text + "  " +
                            lstExams.Items[lstExams.SelectedIndices[0]].SubItems[0].Text + "  " +
                            lstExams.Items[lstExams.SelectedIndices[0]].SubItems[1].Text + "  " +
                            lstExams.Items[lstExams.SelectedIndices[0]].SubItems[2].Text;
                lstFichas.Items.Add("..");
                DataTable dt;

                XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
                TextReader tr = new StreamReader(lstExams.Items[lstExams.SelectedIndices[0]].SubItems[4].Text);
                MensagemDOHS msgDOHS = (MensagemDOHS)xs.Deserialize(tr);
                tr.Close();
                
                MensagemDOHSExamesDOHS exameDOHS = msgDOHS.ExamesDOHS[0];
                string dataExame = Convert.ToDateTime(exameDOHS.Cabecalho.DataLevantamento).ToString("dd/MM/yyyy");

                foreach (MensagemDOHSExamesDOHSLoteGuiasGuia guia in ((MensagemDOHSExamesDOHSLoteGuias)exameDOHS.Item).Guia)
                {
                    lstFichas.Items.Add(guia.InfoGeral.ID);
                    lstFichas.Items[lstFichas.Items.Count - 1].ImageIndex = 1;
                    lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.DataNasc.Value);
                    lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.DataNasc.atb_Idade);
                    if (guia.InfoGeral.GrupoEtario == st_GrupoEtario.Item1)
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("5 anos");
                    else
                        if (guia.InfoGeral.GrupoEtario == st_GrupoEtario.Item2)
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("12 anos");
                        else
                            if (guia.InfoGeral.GrupoEtario == st_GrupoEtario.Item3)
                                lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("15 anos");
                            else
                                if (guia.InfoGeral.GrupoEtario == st_GrupoEtario.Item4)
                                    lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("35-44 anos");
                                else
                                    if (guia.InfoGeral.GrupoEtario == st_GrupoEtario.Item5)
                                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("65-74 anos");
                    if (guia.InfoGeral.Sexo == "1")
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("M");
                    else
                        if (guia.InfoGeral.Sexo == "2")
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("F");
                    dt = appData.Commands.buscaRegistro("GrupoEtnico", "GrupoEtnico", guia.InfoGeral.GrupoEtnico, dataExame);
                    if (dt.Rows.Count == 0)
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.GrupoEtnico);
                    else
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(dt.Rows[0].ItemArray[2].ToString());
                    dt = appData.Commands.buscaRegistro("Ocupacao", "Ocupacao", guia.InfoGeral.Ocupacao, dataExame);
                    if (dt.Rows.Count == 0)
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.Ocupacao);
                    else
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(dt.Rows[0].ItemArray[2].ToString());
                    if (guia.InfoGeral.ContraIndicacao != null)
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.ContraIndicacao.Value);
                    else
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("Não Há Contra-Indicação");
                    if (guia.InfoGeral.Duplicata == "1")
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("X");
                    else
                        lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add("");
                    if (guia.InfoGeral.OutrosDados1 != null)
                    {
                        dt = appData.Commands.buscaRegistro("OutrosDados", "OutrosDados", guia.InfoGeral.OutrosDados1.Value, dataExame);
                        if (dt.Rows.Count == 0)
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.GrupoEtnico);
                        else
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(dt.Rows[0].ItemArray[2].ToString());
                    }
                    if (guia.InfoGeral.OutrosDados2 != null)
                    {
                        dt = appData.Commands.buscaRegistro("OutrosDados", "OutrosDados", guia.InfoGeral.OutrosDados2.Value, dataExame);
                        if (dt.Rows.Count == 0)
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(guia.InfoGeral.OutrosDados2.Value);
                        else
                            lstFichas.Items[lstFichas.Items.Count - 1].SubItems.Add(dt.Rows[0].ItemArray[2].ToString());
                    }
                }
                lstFichas.Visible = true;
            }
        }

        private void lstFichas_DoubleClick(object sender, EventArgs e)
        {
            if (lstFichas.SelectedIndices[0] == 0)
            {
                lblTopo.Text = "Exames Realizados";
                lstFichas.Visible = false;
                lstFichas.Items.Clear();
            }
        }

        #region Novo Documento

        private void excel972003ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveExportExcel2007.ShowDialog() == DialogResult.OK)
                this.Export("C:\\Documents and Settings\\Pinda\\Meus documentos\\Visual Studio 2008\\Projects\\ProjetoOMS\\DesktopDOHS\\BaseSpreadSheetOMS\\BaseSpreadSheetOMS.xls",
                    saveExportExcel972003.FileName);
        }

        private void excel2007ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveExportExcel2007.ShowDialog() == DialogResult.OK)
                this.Export("C:\\Documents and Settings\\Pinda\\Meus documentos\\Visual Studio 2008\\Projects\\ProjetoOMS\\DesktopDOHS\\BaseSpreadSheetOMS\\BaseSpreadSheetOMS.xlsx",
                    saveExportExcel2007.FileName);
        }

        #endregion

        #region Incluir Documento

        private void excel972003ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openExportExcel972003.ShowDialog() == DialogResult.OK)
                this.Export("C:\\Documents and Settings\\Pinda\\Meus documentos\\Visual Studio 2008\\Projects\\ProjetoOMS\\DesktopDOHS\\BaseSpreadSheetOMS\\BaseSpreadSheetOMS.xls",
                    openExportExcel972003.FileName);
        }

        private void excel2007ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openExportExcel2007.ShowDialog() == DialogResult.OK)
                this.Export("C:\\Documents and Settings\\Pinda\\Meus documentos\\Visual Studio 2008\\Projects\\ProjetoOMS\\DesktopDOHS\\BaseSpreadSheetOMS\\BaseSpreadSheetOMS.xlsx",
                    openExportExcel2007.FileName);
        }

        #endregion


    }
}
